package vic.sendreceive;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Vector;

import vic.logic.ILogic;

public class SendReceiveServer extends Thread{
	public ILogic gameView;
	protected ServerSocket socketServer;
    protected int port;
    protected boolean listening;    
    protected Vector<SendReceiveConnection> clientConnections;
    
    public SendReceiveServer(int serverPort,ILogic gameView) {
    	this.gameView = gameView;
        this.port = serverPort;
        this.clientConnections = new Vector<SendReceiveConnection>();
        this.listening = false;
    }
    
    public int getPort() {
        return this.port;
    }
    
    public int getClientCount() {
        return this.clientConnections.size();
    }

    public void run() {        
        try {
			this.socketServer = new ServerSocket(this.port);
		} catch (IOException e) {
			e.printStackTrace();
		}
        this.listening = true;
        while (listening) {                
            Socket socket;
			try {
				socket = this.socketServer.accept();
				SendReceiveConnection socketConnection = new SendReceiveConnection(socket, this);
	            socketConnection.start();
	            this.clientConnections.add(socketConnection);
			} catch (IOException e) {
				e.printStackTrace();
			}
        };
    }
    public void sendPrivate(SendReceiveConnection clientConnection,String msg) {       
    	clientConnection.send(msg);        
    }
    public void sendAll(String msg) {
        for (int i = 0; i < this.clientConnections.size(); i++) {
            SendReceiveConnection client = this.clientConnections.get(i);
            client.send(msg);
        }
    }
    public boolean remove(SocketAddress remoteAddress) {
        for (int i = 0; i < this.clientConnections.size(); i++) {
            SendReceiveConnection client = this.clientConnections.get(i);
            if (client.getRemoteAddress().equals(remoteAddress)) {
                this.clientConnections.remove(i);
                sendAll(remoteAddress + " has disconnected.");
                return true;
            }
        }
        return false;
    }

    protected void finalize() {	 
        try {
			this.socketServer.close();			
		} catch (IOException e) {
			e.printStackTrace();
		}
        this.listening = false;
    }
}
